﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Codeblack.TfsScrumboard.Extensions;
using Codeblack.TfsScrumboard.Interfaces;

namespace Codeblack.TfsScrumboard.Entities
{
    public class Workitem
    {
        private IScrumboardSettings _scrumboardSettings = null;

        public Workitem(Project project, WorkItem workItem, IScrumboardSettings scrumboardSettings)
        {
            this._scrumboardSettings = scrumboardSettings;

            this.Project = project;
            this.WorkItem = workItem;

            this.WorkItemType = workItem.GetFieldValue<string>(scrumboardSettings.Workitems.TypeFieldName);
            this.ID = workItem.GetFieldValue<int>(scrumboardSettings.Workitems.IDFieldName);
            this.Title = workItem.GetFieldValue<string>(scrumboardSettings.Workitems.TitleFieldName);
            this.StoryPoints = workItem.GetFieldValue<double>(scrumboardSettings.Workitems.StoryPointsFieldName);
            this.Status = workItem.GetFieldValue<string>(scrumboardSettings.Workitems.StatusFieldName);
            this.IterationPath = workItem.GetFieldValue<string>(scrumboardSettings.Workitems.IterationPathFieldName);
            this.AssignedTo = workItem.GetFieldValue<string>(scrumboardSettings.Workitems.AssignedToFieldName);
            this.Priority = workItem.GetFieldValue<int>(scrumboardSettings.Workitems.PriorityFieldName);
        }

        public Project Project { get; private set; }
        public WorkItem WorkItem { get; private set; }
        
        public string WorkItemType { get; private set; }
        public int ID { get; protected set; }
        public string Title { get; set; }
        public double StoryPoints { get; set; }
        public string Status { get; set; }
        public string IterationPath { get; set; }
        public string AssignedTo { get; set; }
        public int Priority { get; set; }

        public void Save(string comment)
        {
            if (!string.IsNullOrEmpty(comment))
            {
                this.WorkItem.History += comment;
            }

            this.WorkItem.SetFieldValue(this._scrumboardSettings.Workitems.IterationPathFieldName, this.IterationPath);
            this.WorkItem.SetFieldValue(this._scrumboardSettings.Workitems.PriorityFieldName, this.Priority);

            this.WorkItem.Save();
        }
    }
}
